//开发环境的插件
import type { Plugin } from 'vite'
import type { AddressInfo } from 'net'
import { spawn } from 'child_process'
import fs from 'fs'

const buildFrame = () => {
  require('esbuild').buildSync({
    entryPoints: ['src/frame.ts'],
    bundle: true,
    outfile: 'dist/frame.js',
    platform: 'node',
    target: 'node12',
    format: 'cjs',
    external: ['electron']
  })
}

export const ElectronDevPlugin = (): Plugin => {
  return {
    name: 'electron-dev',
    configureServer(server: any) {
      buildFrame()
      server?.httpServer?.once('listening', () => {
        const addressInfo: AddressInfo = server.httpServer?.address()
        //拼接ip地址
        const ip = 'http://localhost:' + addressInfo.port
        //第一个参数是electron的路径，第二个参数是electron的启动参数
        //require('electron') 返回的是一个路径
        //electron不认识ts, 需要编译成js
        let ElectronProcess = spawn(require('electron'), ['dist/frame.js', ip])
        fs.watchFile('src/frame.ts', () => {
          //杀死electron进程
          ElectronProcess.kill()
          //重新编译electron
          buildFrame()
          ElectronProcess = spawn(require('electron'), ['dist/frame.js', ip])
        })
        ElectronProcess.stderr.on('data', (data) => {
          console.log('日志', data.toString())
        })
        console.log(ip)
      })
    }
  }
}
